package cn.unknowpupil.init.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;


/**
 * created at 2020/9/10 by w10g <br>
 * Initialize QiniuUtils model <br>
 * <p>
 * * 七牛云工具类
 * * Zone.zone0:华东
 * * Zone.zone1:华北
 * * Zone.zone2:华南
 * * Zone.zoneNa0:北美
 * * ———http上传，自动识别上传区域——
 * * Zone.httpAutoZone
 * * ———https上传，自动识别上传区域—— //Zone.httpsAutoZone
 * * Configuration cfg = new Configuration(Zone.zone2());其中Configuration中的Zone.zone2()可以改为Zone.zone0()
 * </p>
 *
 * @author unknowpupil
 * @since 0.0.2
 */
public class QiniuUtils {
    private final static Logger log = LoggerFactory.getLogger(QiniuUtils.class);

    private static String accessKey = "9Mycj_-gOGsKca7VSp8bikAAzfsccv9z-gHYof0y";
    private static String secretKey = "qYlexkSZB3aBYtHdPu0snRkCbmgkOBtRlHzK-Ng3";
    /**
     * 空间名称
     */
    private static String bucket = "gaogedianzi";
    private static long ex_time = 3600;

    /**
     * 获取上传文件的token
     *
     * @param isTemp 是否临时token 默认有效时间 3600s
     * @return
     */
    public static String getUpToken(Boolean isTemp) {
        Auth auth = Auth.create(accessKey, secretKey);
        if (isTemp) {
            return auth.uploadToken(bucket, null, ex_time, new StringMap());
        }
        return auth.uploadToken(bucket);
    }


    /**
     * 外链域名
     */
    public static String domain = "http://qiniu.gravitation.yunfanda.com/";

    public static void upload2Qiniu(String filePath, String fileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(filePath, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException ex) {
            Response r = ex.response;
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    //上传文件
    public static String upload2Qiniu(byte[] bytes, String fileName) {

        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            //返回文件完整路径
            return domain + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
                return "";
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return "";
    }

    //删除文件
    public static void deleteFileFromQiniu(String fileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        String key = fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, key);
            log.info("删除成功");
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }

    /**
     * created at 2020/9/11 by w10g <br>
     * Initialize method inputStreamUpload ...<br>
     * <p>
     * 数据流上传
     * </p>
     *
     * @param bytes
     * @param fileName
     * @return void
     * @author w10g
     * @since 0.0.1
     */
    public static String inputStreamUpload(byte[] bytes, String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(byteInputStream, fileName, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return domain + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return null;
    }

    /**
     * Created at 2020/9/11 by w10g <br>
     * Initialize method breakPoint ...<br>
     * <p>
     * 断点续上传
     * </p>
     *
     * @param bytes
     * @param fileName
     * @return void
     * @author w10g
     * @since 0.0.1
     */
    public static String breakPoint(byte[] bytes, String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释

        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        String localTempDir = Paths.get(System.getProperty("java.io.tmpdir"), bucket).toString();
        try {
            //设置断点续传文件进度保存目录
            FileRecorder fileRecorder = new FileRecorder(localTempDir);
            UploadManager uploadManager = new UploadManager(cfg, fileRecorder);
            try {
                Response response = uploadManager.put(byteInputStream, fileName, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);

                return domain + putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        deleteFileFromQiniu("share_bk_49948187207598941936");

    }

    /**
     * 七牛云上传图片
     *
     * @param localFilePath
     * @return
     */
    public static String uoloapQiniu(File localFilePath, String fileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        String result = null;
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            log.info("{七牛图片上传key: " + putRet.key + ",七牛图片上传hash: " + putRet.hash + "}");
            result =  putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
//            System.err.println(r.toString());
//            try {
//                System.err.println(r.bodyString());
//            } catch (QiniuException ex2) {
//                //ignore
//            }
            result = null;
        }
        return result;
    }



    public static void type(MultipartFile file) {
        //获取文件全名
        file.getOriginalFilename();
        //首先判断是不是空的文件
        if (!file.isEmpty()) {
            //对文文件的全名进行截取然后在后缀名进行删选。
            int begin = file.getOriginalFilename().indexOf(".");
            int last = file.getOriginalFilename().length();
            //获得文件后缀名
            String a = file.getOriginalFilename().substring(begin, last);
            System.out.println(a);
        }
    }
}
